package com.iotechn.unimall.admin.api.article;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dobbinsoft.fw.core.exception.AdminServiceException;
import com.dobbinsoft.fw.core.exception.ServiceException;
import com.dobbinsoft.fw.core.util.SessionUtil;
import com.dobbinsoft.fw.support.model.Page;
import com.iotechn.unimall.data.domain.ArticleClassDO;
import com.iotechn.unimall.data.domain.ArticleDO;
import com.iotechn.unimall.data.dto.AdminDTO;
import com.iotechn.unimall.data.dto.ArticleDTO;
import com.iotechn.unimall.data.dto.UserDTO;
import com.iotechn.unimall.data.enums.ArticleType;
import com.iotechn.unimall.data.exception.ExceptionDefinition;
import com.iotechn.unimall.data.mapper.ArticleClassMapper;
import com.iotechn.unimall.data.mapper.ArticleMapper;
import com.iotechn.unimall.data.vo.TreeVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class  ArticleServiceImpl extends ServiceImpl<ArticleMapper, ArticleDO> implements ArticleService {

    @Autowired
    private SessionUtil<UserDTO, AdminDTO> sessionUtil;

    @Resource
    private ArticleClassMapper articleClassMapper;

    @Override
    public Page<ArticleDTO> page(String searchValue, String articleClassId, Integer status, String startTime, String endTime, Integer page, Integer limit, Long adminId) throws ServiceException {
        QueryWrapper<ArticleDO> wrapper = new QueryWrapper<>();
        //根据标题或内容模糊查询
        if (ObjectUtil.isNotEmpty(searchValue)) {
            wrapper.and(q -> q.like("article.title", searchValue)
                    .or().like("article.content", searchValue));
        }
        //查询类型
        if (ObjectUtil.isNotEmpty(articleClassId)) {
            wrapper.eq("article.article_class_id",articleClassId);
        }
        //查询状态
        if (ObjectUtil.isNotEmpty(status)) {
            wrapper.eq("article.`status`",status);
        }
        //查询时间
        if((ObjectUtil.isNotEmpty(startTime) && (ObjectUtil.isNotEmpty(endTime)))){
            wrapper.between("article.gmt_create",startTime,endTime);
        }
        //按照最新的排序
        wrapper.orderByDesc("article.gmt_create");
        return baseMapper.pageArticle(Page.div(page,limit, ArticleDTO.class),wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ArticleDTO create(ArticleDO articleDO, Long adminId) throws ServiceException {
        Date date = new Date();
        articleDO.setGmtCreate(date);
        AdminDTO admin = sessionUtil.getAdmin();
        articleDO.setGmtCreateUser(admin.getUsername());
        articleDO.setHeat(0L);
        //默认状态，未发布
        articleDO.setStatus(0);
        if (baseMapper.insert(articleDO) <= 0) {
            throw new AdminServiceException(ExceptionDefinition.ADMIN_UNKNOWN_EXCEPTION);
        }
        ArticleDTO articleDTO = new ArticleDTO();
        BeanUtils.copyProperties(articleDO,articleDTO);
        return articleDTO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ArticleDTO edit(ArticleDO articleDO, Long adminId) throws ServiceException {
        Date date = new Date();
        articleDO.setGmtUpdate(date);
        if (baseMapper.updateById(articleDO) <= 0) {
            throw new AdminServiceException(ExceptionDefinition.ADMIN_UNKNOWN_EXCEPTION);
        }
        ArticleDTO articleDTO = new ArticleDTO();
        BeanUtils.copyProperties(articleDO,articleDTO);
        return articleDTO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String delete(Long id, Long adminId) throws ServiceException {
        if (baseMapper.deleteById(id) <= 0) {
            throw new AdminServiceException(ExceptionDefinition.ADMIN_UNKNOWN_EXCEPTION);
        }
        return "ok";
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String issue(Long id, Long adminId) throws ServiceException {
        ArticleDO articleDO = new ArticleDO();
        articleDO.setId(id);
        articleDO.setStatus(ArticleType.HAVE_PUBLISHED.getCode());
        if (baseMapper.updateById(articleDO) <= 0) {
            throw new AdminServiceException(ExceptionDefinition.ADMIN_UNKNOWN_EXCEPTION);
        }
        return "ok";
    }

    @Override
    public ArticleDO detail(Long id, Long adminId) throws ServiceException {
        return baseMapper.selectById(id);
    }

    @Override
    public List<TreeVO> tree(Long adminId) throws ServiceException {
        List<ArticleDO> articleDOS = baseMapper.selectList(new QueryWrapper<>());
        List<ArticleClassDO> articleClassDOS = articleClassMapper.selectList(new QueryWrapper<>());
        return selectArticle(articleDOS, articleClassDOS);
    }

    private List<TreeVO> selectArticle(List<ArticleDO> articleDOS, List<ArticleClassDO> articleClassDOS) {
        List<TreeVO> treeVOS = articleClassDOS.stream().map(o -> {
            TreeVO treeVO = new TreeVO();
            treeVO.setLabel(o.getName());
            treeVO.setValue(o.getId());
            List<TreeVO> articles = articleDOS.stream().filter(item -> item.getArticleClassId().equals(treeVO.getValue())).map(p -> {
                TreeVO article = new TreeVO();
                article.setValue(p.getId());
                article.setLabel(p.getTitle());
                return article;
            }).collect(Collectors.toList());
            treeVO.setChildren(articles);
            return treeVO;
        }).collect(Collectors.toList());
        return treeVOS;
    }
}
